<template>
    <div class="sales-record-container">
        <h2>销售单记录</h2>
        <!-- 搜索区域 -->
        <div class="search-bar">
            <el-form :model="form" label-width="auto" inline>
                <!-- 单据号/客户名 -->
                <el-form-item>
                    <el-input v-model="form.text" placeholder="请输入单据号或客户名或备注" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="有效日期：" prop="dateRange">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 413px;" @change="handleDateChange"
                        value-format="YYYY-MM-DD" />
                </el-form-item>


                <!-- 销售人员 -->
                <el-form-item label="销售员：" prop="workName" v-if="count != 6">
                    <el-input v-model="form.workName" placeholder="业务员" style="width: 160px;" readonly />
                </el-form-item>

                <el-form-item label="销售员：" prop="workName" v-else>
                    <el-select v-model="form.workNumber" placeholder="请选择" clearable style="width: 160px;">
                        <el-option v-for="salesPerson in salesPersonList" :key="salesPerson.id"
                            :label="salesPerson.name" :value="salesPerson.id" />
                    </el-select>
                </el-form-item>


                <!-- 收款状态 -->
                <el-form-item label="收款状态:">
                    <el-select v-model="form.state" placeholder="" clearable style="width: 160px">
                        <el-option label="未收款" value="0" />
                        <el-option label="部分收款" value="1" />
                        <el-option label="全部收款" value="2" />
                    </el-select>
                </el-form-item>

                <el-form-item label="审核状态：">
                    <el-select v-model="form.auditStatus" placeholder="(空)" clearable style="width: 160px;">
                        <el-option label="已保存" value="0" />
                        <el-option label="待审核" value="1" />
                        <el-option label="已审核" value="2" />
                        <el-option label="已作废" value="3" />
                    </el-select>
                </el-form-item>

                <!-- 退货状态 -->
                <el-form-item label="退货状态:">
                    <el-select v-model="form.returnState" placeholder="" clearable style="width: 160px">
                        <el-option label="未退货" value="0" />
                        <el-option label="部分退货" value="1" />
                        <el-option label="全部退货" value="2" />
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="仓库：">
                    <el-input v-model="input" readonly placeholder="选择仓库" @click="warehouseVisible = true"
                        style="width: 160px" />
                </el-form-item>

                <el-form-item label="商品：">
                    <el-input v-model="goodsInput" readonly placeholder="选择商品" @click="openGoodsDialog"
                        style="width: 160px" />
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作 -->
        <div v-if="!props.selectable" class="action-bar" style="float: right;">
            <div class="right-action-buttons">
                <el-button type="primary" @click="addSalesSlip">新增</el-button>
                <el-dropdown placement="bottom-end">
                    <el-button> 审核 <el-icon>
                            <ArrowDown />
                        </el-icon> </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item>反审核</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-dropdown placement="bottom-end">
                    <el-button> 导入 <el-icon>
                            <ArrowDown />
                        </el-icon> </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item>导出</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-button @click="batchDelete" :disabled="selectedRows.length === 0">删除</el-button>
            </div>
        </div>

        <div style="clear: both"></div>
        <!-- 主要表格 -->
        <div class="table-container">
            <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="70" align="center" />

                <el-table-column label="操作" width="140" align="center">
                    <template #default="scope">
                        <template v-if="props.selectable">
                            <el-button size="mini" type="text" @click="selectSalesSlip(scope.row)">选择</el-button>
                        </template>
                        <template v-else>
                            <el-button size="mini" type="text" @click="editQuote(scope.row)">编辑</el-button>
                            <el-button size="mini" type="text" @click="deleteQuote(scope.row)">删除</el-button>
                        </template>
                    </template>
                </el-table-column>

                <el-table-column label="单据日期" prop="date" width="120" sortable />
                <el-table-column label="单据编号" prop="code" width="160" sortable />
                <el-table-column label="销售人员" prop="workName" width="120" sortable />
                <el-table-column label="客户" prop="customerName" width="120" sortable />
                <el-table-column label="客户类别" prop="customerType" width="120" />
                <el-table-column label="客户地址" prop="customer_address" width="180" show-overflow-tooltip />

                <el-table-column label="审核状态" prop="auditStatus" width="120" sortable>
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.auditStatus == '2' || scope.row.auditStatus == '0' ? 'success' : scope.row.auditStatus == '3' ? 'warning' : 'danger'"
                            size="small">
                            {{ auditStatusMap[scope.row.auditStatus] || scope.row.auditStatus }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="收款状态" prop="state" width="120" sortable>
                    <template #default="scope">
                        <el-tag :type="scope.row.state == '2' ? 'success' : 'warning'" size="small">
                            {{ statusMap[scope.row.state] || scope.row.state }}

                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="交货方式" prop="delivery" width="120">
                    <template #default="scope">
                        {{ deliveryMap[scope.row.delivery] || scope.row.delivery }}
                    </template>
                </el-table-column>
                <el-table-column label="交货日期" prop="productDate" width="120" sortable />
                <el-table-column label="退货状态" prop="returnState" width="120" sortable>
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.returnState == '2' ? 'danger' : scope.row.returnState == '1' ? 'warning' : 'success'"
                            size="small">
                            {{ returnStateMap[scope.row.returnState] || scope.row.returnState }}
                        </el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="关联报价单号" prop="quotationCode" width="180" /> -->
                <el-table-column label="关联销货退货单号" prop="returnCode" width="180">
                    <template #default="scope">
                        <div v-if="scope.row.returnCode">
                            <el-link v-for="code in scope.row.returnCode.split(' ')" :key="code" type="primary"
                                @click="viewReturnOrder(code)" :underline="false"
                                style="display: block; margin-bottom: 2px;">
                                {{ code }}
                            </el-link>
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>

                <el-table-column label="源销货订单号" prop="salesOrderCode" width="180">
                    <template #default="scope">
                        <el-link v-if="scope.row.salesOrderCode" type="primary"
                            @click="viewSalesOrder(scope.row.salesOrderCode)" :underline="false">
                            {{ scope.row.salesOrderCode }}
                        </el-link>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="商品数量" prop="itemCount" width="110" sortable />
                <el-table-column label="折后金额" prop="salesAmount" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.salesAmount }}
                    </template>
                </el-table-column>
                <el-table-column label="税额" prop="taxAmount" width="100" sortable>
                    <template #default="scope">
                        {{ scope.row.taxAmount }}
                    </template>
                </el-table-column>

                <el-table-column label="已收款金额" prop="written_off_amount" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.written_off_amount }}
                    </template>
                </el-table-column>
                <el-table-column label="优惠后总额" prop="slipPrice" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.slipPrice }}
                    </template>
                </el-table-column>

                <!-- <el-table-column label="优惠金额" prop="taxCost" width="110" sortable>
                    <template #default="scope">
                        {{ scope.row.taxCost }}
                    </template>
                </el-table-column>
                <el-table-column label="优惠后金额" prop="taxEndCost" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.taxEndCost }}
                    </template>
                </el-table-column> -->
                <!-- <el-table-column label="制单人" prop="checkedBy" width="100" /> -->
                <!-- <el-table-column label="制单时间" prop="createTime" width="150" /> -->
                <el-table-column label="备注" prop="remarks" width="120" />
            </el-table>
        </div>

        <!-- 分页组件 -->
        <div style="float: right; padding-top: 20px;">
            <el-pagination background layout="prev, pager, next,jumper" :total="pageInfo.total"
                :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum" @current-change="changePage" />
        </div>

        <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable
            :show-close="true">
            <!-- 调用仓库的搜索组件 -->
            <WareHouse ref="warehouseRef"
                :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
            <br /><br />
        </el-dialog>

        <GoodsSelectDialog v-model:visible="goodsDialogVisible" :data-source="productDataSource"
            :selected="selectedProducts" @confirm="handleGoodsConfirm" @cancel="handleGoodsCancel" />
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, defineProps, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import WareHouse from '../basic/WareHouse.vue'
import GoodsSelectDialog from '@/util/GoodsSelectDialog.vue'
import axios from "axios";

const router = useRouter()

const count = sessionStorage.getItem("count")
const staffName = sessionStorage.getItem("name")

//选择模式
const props = defineProps({
    selectable: {
        type: Boolean,
        default: false
    },
    preFilterCustomerId: {
        type: [String, Number],
        default: ''
    }
})

// 选择销售单
const selectSalesSlip = (row) => {
    emit('select', row)
}

const emit = defineEmits(['select'])
const addSalesSlip = () => {
    router.push({ name: 'salesSlip' });
};

// 打开仓库对话框
let warehouseVisible = ref(false)

let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
    if (!newVisible) {
        if (warehouseRef.value) {
            form.warehouse = warehouseRef.value.selectedArray.map(item => item.name).join(',')
            warehouseRef.value.clearSelected();
        }
    }
})


// 控制商品对话框弹窗显示
const goodsDialogVisible = ref(false)

// 商品数据源
const productDataSource = ref([
])

// 已选商品
const selectedProducts = ref([])

// // 打开商品选择弹窗
// const openGoodsDialog = () => {
//     goodsDialogVisible.value = true
// }

// 确认选择商品
const handleGoodsConfirm = (selected) => {
    selectedProducts.value = selected
    // 将选中的商品名称显示在输入框中
    if (selected && selected.length > 0) {
        form.product = selected.map(item => item.name).join(',')
    } else {
        form.product = ''
    }
    goodsDialogVisible.value = false
}

// 取消选择
const handleGoodsCancel = () => { }

const dateRange = ref([])
// 处理日期变化
const handleDateChange = (val) => {
    if (val && val.length === 2) {
        form.start_date = val[0]
        form.end_date = val[1]
    } else {
        form.start_date = ''
        form.end_date = ''
    }
}

// 表单数据
const form = reactive({
    text: "",
    start_date: '',
    end_date: '',
    workNumber: "",
    workName: staffName,
    state: '',
    auditStatus: "",
    returnState: "",
    warehouse: "",
    product: "",
    customerName: "",
    customerId: ""
});


// 表格数据（扩展字段）
const tableData = ref([
]);

// 分页信息
const pageInfo = reactive({
    list: [],
    total: 0,
    pageSize: 5,
    pageNum: 1,
    pages: 0
});
// 切换页码
const changePage = (newPage) => {
    pageInfo.pageNum = newPage
    onSubmit()
};

// 查询
const onSubmit = async () => {
    // 如果是选择模式且有预设客户，强制过滤
    if (props.selectable && props.preFilterCustomerId) {
        form.customerId = props.preFilterCustomerId
    }

    const response = await axios.get('/api/sales/selectSlipList', {
        params: {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            text: form.text,
            state: form.state,
            start_date: form.start_date ? form.start_date : null,
            end_date: form.end_date ? form.end_date : null,
            workNumber: form.workNumber,
            auditStatus: props.selectable ? '2' : form.auditStatus,
            warehouse: form.warehouse,
            returnState: form.returnState,
            product: form.product,
            customerId: props.selectable ? props.preFilterCustomerId : form.customerId,
            isReturn: 0,
        }
    })

    if (response.data.code == 200) {
        console.log('查询结果:', response.data)
        tableData.value = response.data.selectSlipList.list
        pageInfo.total = response.data.selectSlipList.total
        pageInfo.pageNum = response.data.selectSlipList.pageNum
        pageInfo.pageSize = response.data.selectSlipList.pageSize
        pageInfo.pages = response.data.selectSlipList.pages
    } else {
        ElMessage.error("查询失败: " + response.data.message)
    }
};
//重新选择客户刷新
watch(
    () => props.preFilterCustomerId,
    (newVal, oldVal) => {
        if (props.selectable && newVal !== oldVal) {
            pageInfo.pageNum = 1
            onSubmit() // 重新查询
        }
    }
)
//cz
const resetForm = () => {
    Object.keys(form).forEach((key) => {
        if (typeof form[key] === "string") {
            form[key] = "";
        } else if (Array.isArray(form[key])) {
            form[key] = [];
        }
    });
    dateRange.value = [];
};

const selectedRows = ref([])

// 表格事件
const handleSelectionChange = (val) => {
    selectedRows.value = val
};

// 修改 
const editQuote = (row) => {
    router.push({
        name: 'salesSlip',
        query: {
            code: row.code,
            id: row.id,
            from: 'edit',
            status: row.auditStatus
        }
    })
}
// 删除单个
const deleteQuote = async (row) => {
    await ElMessageBox.confirm(
        `确定要删除报价单 ${row.code} 吗？。`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );

    const response = await axios.post('/api/sales/deleteSalesSlip', [row.id], {
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (response.data.code == 200) {
        ElMessage.success('删除成功');
        onSubmit();
    } else {
        ElMessage.error('删除失败: ' + response.data.message);
    }
};

// 删除
const batchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的报价单');
        return;
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 个报价单吗？此操作不可恢复。`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );

    // 获取选中行的报价单编号 - 这里就是获取id的方式
    const id = selectedRows.value.map(row => row.id);
    const response = await axios.post('/api/sales/deleteSalesSlip', id, {
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (response.data.code == 200) {
        ElMessage.success('删除成功');
        // 重新加载数据
        onSubmit();
    } else {
        ElMessage.error('删除失败: ' + response.data.message);
    }
};

const salesPersonList = ref([
])

const selectStaff = async () => {
    const response = await axios.get('/api/sales/selectStaff')
    if (response.data.code == 5200) {
        console.log('12', response.data)
        salesPersonList.value = response.data.saleStaffList
    } else {
        ElMessage.error(response.data.msg)
        console.error('获取销售员列表失败：', response.data.message)
    }
}

// 查看关联的销货退货单详情
const viewReturnOrder = (returnCode) => {
    if (returnCode) {
        router.push({
            name: 'returnSlip',
            query: {
                code: returnCode,
                from: 'view'
            }
        })
    }
}

// 查看源销货订单详情
const viewSalesOrder = (salesOrderCode) => {
    if (salesOrderCode) {
        router.push({
            name: 'salesOrder',
            query: {
                code: salesOrderCode,
                from: 'view'
            }
        })
    }
}

// 审核状态
const auditStatusMap = {
    '0': '已保存',
    '1': '待审核',
    '2': '已审核',
    '3': '已驳回'
}

// 交货方式
const deliveryMap = {
    '1': '快递',
    '2': '自提',
    '3': '配送'
}

const statusMap = {
    '0': '未收款',
    '1': '部分收款',
    '2': '全部收款',

}

const returnStateMap = {
    '0': '未退货',
    '1': '部分退货',
    '2': '全部退货'
}
onMounted(() => {
    selectStaff()
    onSubmit()
})
</script>

<style scoped>
.sales-record-container {
    padding: 20px;
    background-color: white;
    min-height: 100vh;
}

.search-bar {
    background: white;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 15px;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
    background: white;
    padding: 10px;
    border-radius: 8px;
}

.action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.right-action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.table-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

/* 响应式 */
@media (max-width: 768px) {

    .search-bar,
    .action-bar {
        flex-direction: column;
        gap: 10px;
    }

    .table-container {
        overflow-x: auto;
    }

    .right-action-buttons {
        flex-direction: column;
        width: 100%;
    }
}
</style>